
import {ajax} from '../../utils/httpRequest.js'

import {URI_SEARCHRESULT} from  '../../api.js'

var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    keyword: '',
    sort: 'zuixin',//默认
    sort_type: -1,
    page: 1,
    limit: 20,
    goods_list: [],
    show_history: true,
    show_result: true,
    history_list: [],
    icon:'',
    show_loading:false,
    text:'正在加载····',
    showGoTop:false,
    show_noData:false,
    sw:true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.val){
      this.setData({
        keyword:options.val
      });
    }
    if(this.data.keyword){
      this.getGoodsList();
    }else{
      this.inputFocus();
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var page = this;
    page.setData({
      history_list: page.getHistoryList(true),
    });
  },
  inputFocus: function () {
    var page = this;
    page.setData({
      show_history: true,
      show_result: false,
    });
  },
  inputBlur: function () {
    var page = this;
    if (page.data.goods_list.length > 0) {
      setTimeout(function () {
        page.setData({
          show_history: false,
          show_result: true,
          show_loading:false
        });
      }, 300);
    }
  },
  inputConfirm: function (e) {
    var page = this;
    var keyword = e.detail.value;
    if (keyword.length == 0)
      return;
    page.setData({
      page: 1,
      keyword: keyword,
      goods_list:[]
    });
    //page.setHistory(keyword);
    page.getGoodsList();
  },
  searchCancel: function () {
    wx.navigateBack({
      delta: 1,
    });
  },
  historyClick: function (e) {
    var page = this;
    var keyword = e.currentTarget.dataset.value;
    if (keyword.length == 0)
      return;
    page.setData({
      page: 1,
      keyword: keyword,
      goods_list:[]
    });
    page.getGoodsList();
  },

  getGoodsList: function () {
    var page = this;
    page.setData({
      show_history: false,
      show_result: true,
    });
    // page.showLoadingBar();
    // page.is_loading = true;
    ajax.get(URI_SEARCHRESULT,{
      title:page.data.keyword,
      orderByTile:page.data.sort == 'zuixin'? '':page.data.sort,
      orderBy:page.data.sort_type==-1?'':page.data.sort_type,
      page:page.data.page,
      accessToken: wx.getStorageSync('accessToken')
    },{},(res)=>{

      if(!page.data.icon){
        icon:res.data.data.ico
      }

      page.setData({
        goods_list:res.data.data.commodityList,
        show_loading:false,
        text:'正在加载····'
      });
      this.setHistory(page.data.keyword);
      page.setData({
        history_list:this.getHistoryList(true)
      });
      this.watchPageData();
      //console.log(page.data.goods_list);
    })
  },

  getMoreGoodsList:function () {
    var page = this;
    ajax.get(URI_SEARCHRESULT,{
      title:page.data.keyword,
      orderByTile:page.data.sort == 'zuixin'? '':page.data.sort,
      orderBy:page.data.sort_type==-1?'':page.data.sort_type,
      page:page.data.page,
      accessToken: wx.getStorageSync('accessToken')
    },{},(res)=>{
      page.setData({
        goods_list:page.data.goods_list.concat(res.data.data.commodityList),
        sw:true,
        show_loading:false
      });
      if(res.data.data.commodityList<page.data.limit){
        page.setData({
          sw:false,
          text:'---暂无数据---'
        })
        setTimeout(()=>{
          page.setData({
            show_loading:false
          });
        },1000);
      }
      //console.log(page.data.goods_list);
    })
  },

  getHistoryList: function (is_desc) {
    is_desc = is_desc || false;
    var history_list = wx.getStorageSync('search_history_list');
    if (!history_list)
      return [];
    if (!is_desc) {
      return history_list;
    }
    //var new_list = [];
   // console.log(history_list);
    // for (var i = history_list.length - 1; i >= 0; i--){
    //   new_list.push(history_list[i]);
    // }
   // console.log(new_list);
    return history_list;
  },
  setHistory: function (keyword) {
    var page = this;
    var history_list = page.getHistoryList();
    history_list.unshift({
      keyword: keyword,
    });
    // for (var i in history_list) {
    //   if (history_list.length <= 20)
    //     break;
    //   history_list.splice(i, 1);
    // }
    wx.setStorageSync('search_history_list', history_list);
  },
  deleteSearchHistory: function () {
    var page = this;
    page.setData({
      history_list: null,
    });
    wx.removeStorageSync("search_history_list");
  },

  sortClick: function (e) {
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
        confirmColor: '#ff474f'
      })
    }
    var page = this;
    var sort = e.currentTarget.dataset.sort;
    var default_sort_type = e.currentTarget.dataset.default_sort_type == undefined ? -1 : e.currentTarget.dataset.default_sort_type;
    var sort_type = page.data.sort_type;
    if (page.data.sort == sort) {
      if (default_sort_type == -1) {
        return;
      }
      if (page.data.sort_type == -1) {
        sort_type = default_sort_type;
      } else {
        sort_type = (sort_type == 'desc' ? 'asc' : 'desc');
      }
    } else {
      sort_type = default_sort_type;
    }

    page.setData({
      sort: sort,
      sort_type: sort_type,
      page:1
    });
    page.getGoodsList();
  },

  //判断有没数据；
  watchPageData(){
    if(this.data.goods_list && this.data.goods_list.length>0){
      this.setData({
        show_noData:false
      })
    } else {
      this.setData({
        show_noData:true
      })
    }
  },


  goTop: function (e) {
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
        confirmColor: '#ff474f'
      })
    }
  },

  onPageScroll(e){
    var scroll = e.scrollTop;
    if(scroll>500){
      this.setData({showGoTop:true})
    }else{
      this.setData({showGoTop:false})
    }
  },


  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

   // console.log(this.data.page);
    this.setData({
      show_loading:true
    });
    if(this.data.sw){
      this.setData({
        page:this.data.page+1
      })
      this.getMoreGoodsList();
    }

  },
  onShareAppMessage: function (res) {
    if(res.form === 'button'){
      //来自页内转发
      console.log(res.target);
    }
    return {
      title:'择天惠-一个做优惠的小程序',
      path:'pages/searchResult/searchResult',
      success:function (res) {
        console.log('转发成功');
      },
      fail:function(err){
        console.log('转发失败')
      }
    }
  }

});